package com.kjj.gift.config;

import com.kjj.gift.constants.GiftAuthConstants;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

//资源服务配置
@Configuration
//开启资源服务配置
@EnableResourceServer
//开启方法授权
@EnableGlobalMethodSecurity(prePostEnabled = true)
public abstract class BaseResourceServerConfig extends ResourceServerConfigurerAdapter {
    @Value("${oauth2.resourceId}")
    private String resourceId;
    @Override
    public abstract void configure(HttpSecurity httpSecurity) throws Exception;


    @Override
    public void configure(ResourceServerSecurityConfigurer configurer) throws Exception {

        //核心在配置校验地址
        configurer.resourceId(resourceId)
                //以jwttoken方式校验权限
//                .tokenStore(tokenstore())
                .tokenStore(tokenstore())
//                .tokenServices(resourceServerTokenServices())//非jwttoken方式,校验token
                .stateless(true);
    }
    // 修改令牌获取方式  使用jwttoken
    @Bean
    public TokenStore tokenstore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        System.out.println(GiftAuthConstants.SIGN_KEY);
        JwtAccessTokenConverter jwtAccessTokenConverter = new JwtAccessTokenConverter();
        //设置JWT签名密钥。它可以是简单的MAC密钥，也可以是RSA密钥
        jwtAccessTokenConverter.setSigningKey(GiftAuthConstants.SIGN_KEY);
        return jwtAccessTokenConverter;
    }

}
